import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from agent import WindowAgent
from selenium.webdriver.common.by import By
import time

print("=== 浏览器自动化示例 ===")

def main():
    agent = WindowAgent()
    
    # 启动浏览器
    if agent.start_browser("chrome"):
        try:
            # 导航到网页
            print("正在打开百度...")
            agent.browser_navigate("https://www.baidu.com")
            time.sleep(3)
            
            # 尝试多个可能的选择器
            selectors = [
                (By.ID, "kw"),
                (By.NAME, "wd"),
                (By.CSS_SELECTOR, "input[name='wd']"),
                (By.CSS_SELECTOR, "#kw")
            ]
            
            success = False
            for by, value in selectors:
                print(f"尝试选择器: {by}={value}")
                if agent.browser_input(by, value, "Python自动化", timeout=5):
                    print("输入成功")
                    success = True
                    break
            
            if success:
                time.sleep(1)
                # 尝试点击搜索按钮
                if agent.browser_click(By.ID, "su", timeout=5):
                    print("点击成功")
                    time.sleep(3)
                    
                    # 截屏
                    if agent.browser_screenshot("search_result.png"):
                        print("截屏成功")
            else:
                print("未找到搜索输入框")
                
        except Exception as e:
            print(f"错误: {e}")
        finally:
            # 关闭浏览器
            print("关闭浏览器...")
            time.sleep(2)
            agent.close_browser()

if __name__ == "__main__":
    main()
